import type { FormInstance, FormProps, ModalProps } from 'antd';
import { Form, Modal } from 'antd';
import type { FC, ReactNode } from 'react';
import { useEffect } from 'react';

type TProps = {
  visible: boolean;
  confirmLoading?: boolean; // 提交loading
  title?: string;
  children?: ReactNode;
  onCancel?: TAnyFunction;
  onSubmit?: TAnyFunction; // 表单提交
  formRef?: FormInstance; // 表单实例
  currentData?: any;
  formProps?: FormProps; // 继承Form表单属性
} & ModalProps; // 继承Modal属性

const CommonModalForm: FC<TProps> = (props) => {
  const {
    visible,
    title = '',
    confirmLoading,
    children,
    onCancel,
    onSubmit,
    formProps,
    formRef,
    ...restProps
  } = props;

  // modal窗口点击确定
  const handleSubmit = () => {
    if (formRef) {
      formRef.submit();
    }
  };

  // 提交表单
  const handleFinish = (values: any) => {
    onSubmit && onSubmit(values);
  };

  const modalFooter = { onCancel, onOk: handleSubmit };

  useEffect(() => {
    if (!visible) {
      // modal关闭后重置表单
      formRef && formRef.resetFields();
    }
  }, [visible, formRef]);

  return (
    <Modal
      forceRender
      destroyOnClose
      open={visible}
      title={title}
      confirmLoading={confirmLoading}
      {...modalFooter}
      {...restProps}
    >
      <Form form={formRef} onFinish={handleFinish} autoComplete="off" {...formProps}>
        {children}
      </Form>
    </Modal>
  );
};

export default CommonModalForm;
